package blue.webserver;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
//import com.sun.net.httpserver.Headers;


public class FileHandler implements HttpHandler {
	private String root_dir_;
	
	public FileHandler(String root_dir){
		root_dir_ = root_dir;
	}
	
	private String getFileType(String path){
		String file_type = null;
        if (path.endsWith(".js"))
        	file_type = "text/javascript";
        else if (path.endsWith(".html"))
        	file_type = "text/html";
        else if (path.endsWith(".css"))
        	file_type = "text/css";
        else if (path.endsWith(".json"))
        	file_type = "application/json";
        else if (path.endsWith(".png"))
        	file_type = "image/png";
        else if (path.endsWith(".jpeg"))
        	file_type = "image/jpeg";
        
        return file_type;
	}
	
	private String pathTransform(String path) {
		String sys_sep = File.separator;
		path = path.replace("\\", sys_sep);
		path = path.replace("/", sys_sep);
		
		return path;
	}
	
	public void handle(HttpExchange t) throws IOException {
		URI uri = t.getRequestURI();
		String file_path = root_dir_+uri.getPath();
		file_path = pathTransform(file_path);		
		File file = new File(file_path).getCanonicalFile();
		if (!file.getPath().startsWith(file_path)) {
			// Suspected path traversal attack: reject with 403 error.
		    String response = "403 (Forbidden)\n";
		    t.sendResponseHeaders(403, response.length());
		    OutputStream os = t.getResponseBody();
		    os.write(response.getBytes());
		    os.close();
		} else if (!file.isFile()) {
		    // Object does not exist or is not a file: reject with 404 error.
		    String response = "404 (Not Found)\n";
		    t.sendResponseHeaders(404, response.length());
		    OutputStream os = t.getResponseBody();
		    os.write(response.getBytes());
		    os.close();
		} else {
		    // Object exists and is a file: accept with response code 200.
	        //Headers head = t.getResponseHeaders();
	        //head.add("Content-Type", mimic_);
			String mime = getFileType(file_path);
			if (mime!=null){
				Headers h = t.getResponseHeaders();
				h.add("Content-Type", mime);
			}

		    t.sendResponseHeaders(200, 0);
		    OutputStream os = t.getResponseBody();
		    FileInputStream fs = new FileInputStream(file);
		    final byte[] buffer = new byte[0x10000];
		    int count = 0;
		    while ((count = fs.read(buffer)) >= 0) {
		    	os.write(buffer,0,count);
		    }
		    fs.close();
		    os.close();
		}
	}
}
